#!/bin/bash

# Copyright (C) 2014-2016 OpenDevise Inc. and the Asciidoctor Project

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# Optimizes and compresses the specified PDF using Ghostscript (gs).
#
# [NOTE]
# You need at least Ghostscript 9.10 in order for page labels defined in the
# PDF to be preserved (e.g., front matter pages numbered using roman numerals).

if [ -z $1 ]; then
   echo "Please supply a PDF file to optimize"
   exit 1
fi

if [ -z $GS ]; then
  GS=gs
fi

FILE=$1
FILE_BASENAME=${FILE%.pdf}
FILE_OPTIMIZED=$FILE_BASENAME-optimized.pdf
FILE_PDFMARK=
if [ -f "$FILE_BASENAME.pdfmark" ]; then
  FILE_PDFMARK="$FILE_BASENAME.pdfmark"
fi
DOWNSAMPLE_IMAGES=true
if [ -z $IMAGE_DPI ]; then
  #IMAGE_DPI=150
  IMAGE_DPI=300
fi

# /prepress defaults (see http://ghostscript.com/doc/current/Ps2pdf.htm)
# -d{Color,Gray,Mono}ImageDownsampleType=/Bicubic
# -dAutoFilter{Color,Gray}Images=true
# -dOptimize=true
# -dEmbedAllFonts=true
# -dSubsetFonts=true
# -dColorConversionStrategy=/LeaveColorUnchanged
# -dUCRandBGInfo=/Preserve
# -dCompressPages=true
#
# other unused settings
# -r72
#
# for info about pdfmarks, see http://milan.kupcevic.net/ghostscript-ps-pdf
#
# to convert to grayscale, add the following (though doesn't always work)
#
# -dProcessColorModel=/DeviceGray \
# -dColorConversionStrategy=/Gray \

ERRFILE=$FILE_BASENAME-ERRS.optimize
"$GS" -q -dNOPAUSE -dBATCH -dSAFER -dNOOUTERSAVE \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
  -dPrinted=false \
  -dCannotEmbedFontPolicy=/Warning \
  -dDownsampleColorImages=$DOWNSAMPLE_IMAGES \
  -dColorImageResolution=$IMAGE_DPI \
  -dDownsampleGrayImages=$DOWNSAMPLE_IMAGES \
  -dGrayImageResolution=$IMAGE_DPI \
  -dDownsampleMonoImages=$DOWNSAMPLE_IMAGES \
  -dMonoImageResolution=$IMAGE_DPI \
  -sOutputFile="$FILE_OPTIMIZED" \
  "$FILE" $FILE_PDFMARK 2> $ERRFILE

status=$?
if test $status -ne 0 ; then
    echo "$0: $GS return status = $status, aborting"
elif grep -q Error $ERRFILE ; then
    echo "$0: $GS succeeded but found Error in $ERRFILE (follows), aborting"
    echo '---------- Errors from $GS ----------'
    grep Error $ERRFILE
    echo '-------------------------------------'
    status=1
else
    rm -f $ERRFILE
fi

exit $status
